#!/bin/bash
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
SFTP_TOOL="$SCRIPT_DIR/../tools/sftp"

# Check if the correct number of arguments is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <version>"
    exit 1
fi

# Get the file name at remote path
FILE_NAME=libhjemalloc_$1.tar
REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/alloc-libs/libhjemalloc_$1.tar

# If the directory don't have the file, download it
if [ -z "$(ls -A $SCRIPT_DIR/$FILE_NAME 2>/dev/null)" ] ; then
    if [ ! -f "$SFTP_TOOL" ]; then
        if [ ! -f ./sftp ]; then
            wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
        fi
        chmod +x sftp
        ./sftp download "$REMOTE_PATH" $SCRIPT_DIR/$FILE_NAME
    else
        "$SFTP_TOOL" download "$REMOTE_PATH" $SCRIPT_DIR/$FILE_NAME
    fi
    if [ $? -ne 0 ]; then
        echo "Download failed"
        exit 1
    fi
fi

echo "Extracting $SCRIPT_DIR/$FILE_NAME to /opt/hygon"
tar -xvf $SCRIPT_DIR/$FILE_NAME -C /opt/hygon
